{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Clique Method Robustness Verification for Tree Ensembles and Gradient Boosted Decision Tree Classifiers"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from xgboost import XGBClassifier\n",
    "import lightgbm\n",
    "import numpy as np\n",
    "from sklearn.ensemble import ExtraTreesClassifier, RandomForestClassifier, GradientBoostingClassifier\n",
    "\n",
    "from art.estimators.classification import XGBoostClassifier, LightGBMClassifier, SklearnClassifier\n",
    "from art.utils import load_dataset\n",
    "from art.metrics import RobustnessVerificationTreeModelsCliqueMethod\n",
    "\n",
    "import warnings\n",
    "warnings.filterwarnings('ignore')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "NB_TRAIN = 100\n",
    "NB_TEST = 100\n",
    "\n",
    "(x_train, y_train), (x_test, y_test), _, _ = load_dataset('mnist')\n",
    "\n",
    "n_classes = 10\n",
    "n_features = 28 * 28\n",
    "n_train = x_train.shape[0]\n",
    "n_test = x_test.shape[0]\n",
    "x_train = x_train.reshape((n_train, n_features))\n",
    "x_test = x_test.reshape((n_test, n_features))\n",
    "\n",
    "x_train = x_train[:NB_TRAIN]\n",
    "y_train = y_train[:NB_TRAIN]\n",
    "x_test = x_test[:NB_TEST]\n",
    "y_test = y_test[:NB_TEST]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# XGBoost"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Average bound: 0.035996093750000006\n",
      "Verified error at eps: 0.96\n"
     ]
    }
   ],
   "source": [
    "model = XGBClassifier(n_estimators=4, max_depth=6)\n",
    "model.fit(x_train, np.argmax(y_train, axis=1))\n",
    "\n",
    "classifier = XGBoostClassifier(model=model, nb_features=n_features, nb_classes=n_classes)\n",
    "\n",
    "rt = RobustnessVerificationTreeModelsCliqueMethod(classifier=classifier)\n",
    "average_bound, verified_error = rt.verify(x=x_test, y=y_test, eps_init=0.3, nb_search_steps=10, max_clique=2,\n",
    "                                          max_level=2)\n",
    "\n",
    "print('Average bound:', average_bound)\n",
    "print('Verified error at eps:', verified_error)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# LightGBM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1]\tvalid_0's multi_logloss: 2.25471\n",
      "Training until validation scores don't improve for 10 rounds.\n",
      "[2]\tvalid_0's multi_logloss: 2.21845\n",
      "Did not meet early stopping. Best iteration is:\n",
      "[2]\tvalid_0's multi_logloss: 2.21845\n",
      "Average bound: 0.07634765624999999\n",
      "Verified error at eps: 0.85\n"
     ]
    }
   ],
   "source": [
    "train_data = lightgbm.Dataset(x_train, label=np.argmax(y_train, axis=1))\n",
    "test_data = lightgbm.Dataset(x_test, label=np.argmax(y_test, axis=1))\n",
    "\n",
    "parameters = {'objective': 'multiclass',\n",
    "              'num_class': n_classes,\n",
    "              'metric': 'multi_logloss',\n",
    "              'is_unbalance': 'true',\n",
    "              'boosting': 'gbdt',\n",
    "              'num_leaves': 5,\n",
    "              'feature_fraction': 0.5,\n",
    "              'bagging_fraction': 0.5,\n",
    "              'bagging_freq': 0,\n",
    "              'learning_rate': 0.05,\n",
    "              'verbose': 0}\n",
    "\n",
    "model = lightgbm.train(parameters,\n",
    "                       train_data,\n",
    "                       valid_sets=test_data,\n",
    "                       num_boost_round=2,\n",
    "                       early_stopping_rounds=10)\n",
    "\n",
    "classifier = LightGBMClassifier(model=model)\n",
    "\n",
    "rt = RobustnessVerificationTreeModelsCliqueMethod(classifier=classifier)\n",
    "average_bound, verified_error = rt.verify(x=x_test, y=y_test, eps_init=0.3, nb_search_steps=10, max_clique=2,\n",
    "                                          max_level=2)\n",
    "\n",
    "print('Average bound:', average_bound)\n",
    "print('Verified error at eps:', verified_error)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# GradientBoosting"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Average bound: 0.009234374999999996\n",
      "Verified error at eps: 1.0\n"
     ]
    }
   ],
   "source": [
    "model = GradientBoostingClassifier(n_estimators=4, max_depth=6)\n",
    "model.fit(x_train, np.argmax(y_train, axis=1))\n",
    "\n",
    "classifier = SklearnClassifier(model=model)\n",
    "\n",
    "rt = RobustnessVerificationTreeModelsCliqueMethod(classifier=classifier)\n",
    "average_bound, verified_error = rt.verify(x=x_test, y=y_test, eps_init=0.3, nb_search_steps=10, max_clique=2, \n",
    "                                          max_level=2)\n",
    "\n",
    "print('Average bound:', average_bound)\n",
    "print('Verified error at eps:', verified_error)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# RandomForest"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Average bound: 0.019962890624999997\n",
      "Verified error at eps: 1.0\n"
     ]
    }
   ],
   "source": [
    "model = RandomForestClassifier(n_estimators=4, max_depth=6)\n",
    "model.fit(x_train, np.argmax(y_train, axis=1))\n",
    "\n",
    "classifier = SklearnClassifier(model=model)\n",
    "\n",
    "rt = RobustnessVerificationTreeModelsCliqueMethod(classifier=classifier)\n",
    "average_bound, verified_error = rt.verify(x=x_test, y=y_test, eps_init=0.3, nb_search_steps=10, max_clique=2, \n",
    "                                          max_level=2)\n",
    "\n",
    "print('Average bound:', average_bound)\n",
    "print('Verified error at eps:', verified_error)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ExtraTrees"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Average bound: 0.041332031250000026\n",
      "Verified error at eps: 1.0\n"
     ]
    }
   ],
   "source": [
    "model = ExtraTreesClassifier(n_estimators=4, max_depth=6)\n",
    "model.fit(x_train, np.argmax(y_train, axis=1))\n",
    "\n",
    "classifier = SklearnClassifier(model=model)\n",
    "\n",
    "rt = RobustnessVerificationTreeModelsCliqueMethod(classifier=classifier)\n",
    "average_bound, verified_error = rt.verify(x=x_test, y=y_test, eps_init=0.3, nb_search_steps=10, max_clique=2, \n",
    "                                          max_level=2)\n",
    "\n",
    "print('Average bound:', average_bound)\n",
    "print('Verified error at eps:', verified_error)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
